package com.swss.g.assets.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.swss.g.assets.bean.Asset;
import com.swss.g.assets.bean.AstChangeApply;
import com.swss.g.assets.bean.AstChangeFinAduit;
import com.swss.g.assets.bean.AstRange;
import com.swss.g.assets.bean.ChangeAsset;
import com.swss.g.assets.dao.AssetDAO;
import com.swss.g.assets.dao.ChangeAssetDAO;
import com.swss.g.assets.service.ChangeService;
import com.swss.g.base.impl.BaseServiceImpl;
import com.swss.g.dept.bean.Dept;
import com.swss.g.sys.bean.GBCode;
import com.swss.g.sys.dao.GmkDAO;
import com.swss.g.sys.service.CurrentPeriodService;
import com.swss.g.user.bean.User;
import com.swss.util.BeanUtils;
import com.swss.util.DoDate;
import com.swss.util.HqlUtil;
import com.swss.util.Pagination;

public class ChangeServiceImpl extends BaseServiceImpl<ChangeAsset> implements
		ChangeService {

	private AssetDAO assetDao;
	private ChangeAssetDAO changeAssetDao;
	private GmkDAO gmkDao;

	private CurrentPeriodService currentPeriodService;

	public AssetDAO getAssetDao() {
		return assetDao;
	}

	public void setAssetDao(AssetDAO assetDao) {
		
		this.assetDao = assetDao;
	}

	public CurrentPeriodService getCurrentPeriodService() {
		return currentPeriodService;
	}

	public void setCurrentPeriodService(
			CurrentPeriodService currentPeriodService) {
		this.currentPeriodService = currentPeriodService;
	}

	public void goFirstAduit(Asset asset) throws Exception {
		// TODO Auto-generated method stub
		//将审核字段变为2
	}

	public ChangeAssetDAO getChangeAssetDao() {
		return changeAssetDao;
	}

	public void setChangeAssetDao(ChangeAssetDAO changeAssetDao) {
		this.setBaseDao(changeAssetDao);
		this.changeAssetDao = changeAssetDao;
	}
    /**
     * 查询将要处置的资产
     */
	@SuppressWarnings("unchecked")
	public Pagination findChangeApplyByExample(Pagination pagination,
			Asset asset,AstRange astRange, String deptNo,String hqlCondition) throws Exception {
		// TODO Auto-generated method stub
		if (pagination == null) {
			pagination = new Pagination();
		}
		if (asset != null) {
		  if(asset.getAstName()!=null){
			if (!asset.getAstName().equals("") && !asset.getGbClassNo().equals("")) {
				asset.setGbClassNo("");
			}
		  }
		}
		String hql = "FROM Asset a,Dept d WHERE a.deptNo=d.deptNo AND a.aduit=7 AND a.astNo NOT IN(SELECT c.astNo FROM ChangeAsset c)"
				 + HqlUtil.bean2HqlLike(asset,"a");
		if (hqlCondition != null && !hqlCondition.equals("")) {
			hqlCondition = " AND (" + hqlCondition + ")";
		}else{
			hqlCondition="";
		}
		if(astRange!=null){ 
			hql+=HqlUtil.rangeHql(astRange,"a");
		}
		if (!deptNo.trim().equals("00")) {
			hql += " AND a.deptNo LIKE '" + deptNo.trim() + "%'";
		}
		List list = this.getAssetDao().findByHql(
				hql+hqlCondition+ " ORDER BY a." + pagination.getOrderBy() + " "
						+ pagination.getOrderType(), pagination);
		
		List<Asset> assetList = new ArrayList();

		for (int i = 0; i < list.size(); i++) {
			Object[] obj = (Object[]) list.get(i);
			Asset ast = (Asset) obj[0];

			ast.setDept((Dept) obj[1]);
			assetList.add(ast);
		}
		pagination.setResult(assetList);
		
		pagination.setRowcount(this.getAssetDao().findCount(hql));
		return pagination;
	}
    /***
     * 处置申请处理
     */
	public int goApply(AstChangeApply astChangeApply, String auditNoArray,String chageBillNo)
			throws Exception {
		// TODO Auto-generated method stub
		try{
			
			HttpServletRequest request = ServletActionContext.getRequest();
			HttpSession sessions = request.getSession();
			User u = (User) sessions.getAttribute("user");

			String auditNo[] = auditNoArray.split(",");
			Asset asset = null;
			ChangeAsset changeAsset = null;
			List<ChangeAsset> changeAssetList = new ArrayList<ChangeAsset>();
			
			for (int i = 0; i < auditNo.length; i++) {
				asset = this.assetDao.get(Integer.parseInt(auditNo[i]));
				changeAsset=new ChangeAsset();
				//数据对象转换
				BeanUtils.copyProperties(asset,changeAsset);
				//判断(处置方式)现状为 无偿调拨7或内部转移8
				if(astChangeApply.getApplyMethod().equals("6")||astChangeApply.getApplyMethod().equals("7") ){
					changeAsset.setChageDeptName(astChangeApply.getChagedeptName().trim());
					changeAsset.setChageastCount(asset.getAstCount());
				}else if(astChangeApply.getApplyMethod().equals("9")){
					changeAsset.setChageDeptNo(astChangeApply.getChageDeptNo().trim());
					changeAsset.setChageastCount(asset.getAstCount());
					changeAsset.setAduit(5);
				}else if(astChangeApply.getApplyMethod().equals("1")){ //增减值处置
					changeAsset.setChageastCount(astChangeApply.getChageastCount());
					changeAsset.setChagePrice(astChangeApply.getChagePrice());
					changeAsset.setChageAmount(astChangeApply.getChagePrice()*astChangeApply.getChageastCount());
				}else
					changeAsset.setChageastCount(asset.getAstCount());
				//设置处置方式
				changeAsset.setChagedanJuNo(chageBillNo.trim());
				changeAsset.setXz(astChangeApply.getApplyMethod().trim());
				changeAsset.setChangeDate(new DoDate().getDate(new Date()));
				changeAsset.setChagejfly("0");
				changeAsset.setChageReason(astChangeApply.getChageReason().trim());
				changeAsset.setTableType(astChangeApply.getTableType());
				changeAsset.setChageResult(astChangeApply.getApplyResult());
				changeAsset.setApplicant(u.getAccperName());
				changeAsset.setApplicantDate(new DoDate().getDate(new Date()));
				
				//设置处置标记
				if (astChangeApply.getApplyMethod().trim().equals("9")) {
					changeAsset.setAduit(5);
				} else {
					changeAsset.setAduit(1);
				}
				changeAssetList.add(changeAsset);
			}
			  this.getChangeAssetDao().saveAll(changeAssetList);
		}catch(Exception e){
			e.printStackTrace();
			return 1;
		}
		return 0;
	}
   /***
    * 处置changemain 表查询（管理、审核等）
    */
	@SuppressWarnings("unchecked")
	public Pagination findChangeApplyAduitByExample(Pagination pagination,ChangeAsset changeAsset,AstRange astRange,String deptNo,String hqlCondition,int funtype) throws Exception {
		// TODO Auto-generated method stub
		if (pagination == null) {
			pagination = new Pagination();
		}
		if (changeAsset != null) {
			if (changeAsset.getAstName() != null) {
				if (!changeAsset.getAstName().equals("")
						&& !changeAsset.getGbClassNo().equals("")) {
					changeAsset.setGbClassNo("");
				}
			}
		}
		String hql="FROM ChangeAsset chageA,Dept d WHERE chageA.deptNo=d.deptNo";
		if (hqlCondition != null && !hqlCondition.equals("")) {
			hqlCondition = " AND (" + hqlCondition + ")";
		}else{
			hqlCondition="";
		}
		if(astRange!=null){ 
			hql+=HqlUtil.rangeHql(astRange,"chageA");
		}
		if (!deptNo.trim().equals("00")) {
			hql+=" AND chageA.deptNo LIKE '" + deptNo.trim() + "%'";
		}
		// 标记说明： 1.申报管理 2.处置初审3.处置财务审4.处置财务回复5.处置终审
		if (funtype == 1) {
			hql += " AND (chageA.aduit=0 OR chageA.aduit=1)";
		} else if (funtype == 2) {
            hql+=" AND (chageA.aduit=0 OR chageA.aduit=1) AND chageA.xz<>'9'"; //单位内部转移不记处置审核 处置方式(现状)9
		} else if (funtype == 3) {
            hql+=" AND (chageA.aduit=3 OR chageA.aduit=2) AND chageA.xz<>'9'";
		} else if(funtype==4){
			hql+=" AND (chageA.aduit=5 OR chageA.aduit=4) AND chageA.xz<>'9'";
		} else if(funtype==5){
			hql+=" AND (chageA.aduit=5 )";
		} else if(funtype==6){
			hql+=" AND (chageA.aduit=7)";
		}
		hql+= HqlUtil.bean2HqlLike(changeAsset, "chageA");
		System.out.println("*****++"+hql);
		List list = this.getChangeAssetDao().findByHql(
				hql+hqlCondition+ " ORDER BY chageA." + pagination.getOrderBy() + " "
						+ pagination.getOrderType(), pagination);
	//	System.out.println("+++++"+hql);
		List<ChangeAsset> chageassetList = new ArrayList();
		for (int i = 0; i < list.size(); i++) {
			Object[] obj = (Object[]) list.get(i);
			ChangeAsset chageast = (ChangeAsset) obj[0];

			chageast.setDept((Dept) obj[1]);
			chageassetList.add(chageast);
		}
		pagination.setResult(chageassetList);
		pagination.setRowcount(this.getChangeAssetDao().findCount(hql));
		return pagination;
	}

	public int changeAstDeleteAll(String auditNoArray) throws Exception {
		// TODO Auto-generated method stub
		String auditNo[] = auditNoArray.split(",");
		ChangeAsset changeAsset = null;
		List<ChangeAsset> ChangeAssetList = new ArrayList<ChangeAsset>();
		try {
			for (int i = 0; i < auditNo.length; i++) {
				changeAsset = this.getChangeAssetDao().get(Integer.parseInt(auditNo[i]));
				ChangeAssetList.add(changeAsset);
			}
			this.getChangeAssetDao().deleteAll(ChangeAssetList);
		} catch (Exception e) {
			e.printStackTrace();
			return 1;
		}
		return 0;
	}

	@SuppressWarnings("unchecked")
	public ChangeAsset findChageOneById(Integer id) throws Exception {
		// TODO Auto-generated method stub
		StringBuffer hql = new StringBuffer(
				"FROM ChangeAsset chageA,Dept d,GBCode g WHERE chageA.deptNo=d.deptNo AND chageA.gbClassNo=g.ascNo");
		hql.append(" AND chageA.id=" + id);
		List list = this.getAssetDao().findByHql(hql.toString());

		Object[] obj = (Object[]) list.get(0);
		ChangeAsset changeAsset = (ChangeAsset) obj[0];
		changeAsset.setDept((Dept) obj[1]);
		changeAsset.setGbCode((GBCode) obj[2]);

		return changeAsset;
	}

	public int FirstChangeAuditUpdate(String auditNoArray) throws Exception {
		// TODO Auto-generated method stub
		String auditNo[] = auditNoArray.split(",");
		ChangeAsset ChangeAsset = null;
		List<ChangeAsset> changeAssetList = new ArrayList<ChangeAsset>();
		for (int i = 0; i < auditNo.length; i++) {
			ChangeAsset = new ChangeAsset();
			ChangeAsset.setId(Integer.parseInt(auditNo[i]));
			changeAssetList.add(ChangeAsset);
		}
		if (this.changeAssetDao.FirstChangeAuditUpdate(changeAssetList))
			return 0;
		else
			return 1;
	}

	public int FinanceChangeAuditUpdate(String auditNoArray,AstChangeFinAduit astChangeFinAduit) throws Exception {
		// TODO Auto-generated method stub
		String auditNo[] = auditNoArray.split(",");
		ChangeAsset changeAsset = null;
		List<ChangeAsset> changeAssetList = new ArrayList<ChangeAsset>();
		for (int i = 0; i < auditNo.length; i++) {
			changeAsset = new ChangeAsset();
			changeAsset.setId(Integer.parseInt(auditNo[i]));
			
			changeAssetList.add(changeAsset);
		}
		if (this.changeAssetDao.FinanceChangeAuditUpdate(changeAssetList,astChangeFinAduit))
			return 0;
		else
			return 1;
	}

	public int astChangeFinAuditBack(String auditNoArray, String returreas)
			throws Exception {
		// TODO Auto-generated method stub
		String auditNo[] = auditNoArray.split(",");
		ChangeAsset changeasset = null;
		List<ChangeAsset> chageassetList = new ArrayList<ChangeAsset>();
		for (int i = 0; i < auditNo.length; i++) {
			changeasset = new ChangeAsset();
			changeasset.setId(Integer.parseInt(auditNo[i]));
			chageassetList.add(changeasset);
		}
		if (this.changeAssetDao.backAstChangeFinAudit(chageassetList, returreas))
			return 0;
		else
			return 1;
	}
	public int astChangeFinthroughAudit(String auditNoArray) throws Exception {
		// TODO Auto-generated method stub
		String auditNo[] = auditNoArray.split(",");
		ChangeAsset changeasset = null;
		List<ChangeAsset> changeassetList = new ArrayList<ChangeAsset>();
		for (int i = 0; i < auditNo.length; i++) {
			changeasset = new ChangeAsset();
			changeasset.setId(Integer.parseInt(auditNo[i]));
			changeassetList.add(changeasset);
		}
		if (this.changeAssetDao.throughAstChangeFinAudit(changeassetList))
			return 0;
		else
			return 1;
	}
	public int LastChangeAuditUpdate(String auditNoArray) throws Exception {
		// TODO Auto-generated method stub
		String auditNo[] = auditNoArray.split(",");
		ChangeAsset changeAsset = null;
		Asset asset =null;
		try{
		List<ChangeAsset> changeAssetList = new ArrayList<ChangeAsset>();
		List<Asset> assetListUpdate = new ArrayList<Asset>(); 
		List<Asset> assetListDel = new ArrayList<Asset>();
		for (int i = 0; i < auditNo.length; i++) {
			changeAsset = new ChangeAsset();
		    asset = new Asset();
			changeAsset=this.getChangeAssetDao().get(Integer.parseInt(auditNo[i]));
			asset = this.getChangeAssetDao().findOneAstByNo(changeAsset.getAstNo().trim());
			if(changeAsset.getXz().trim().equals("1")){
				if(changeAsset.getChageastCount()!=1){ //默认1 为变动数量，主表审核后不进行运算
				asset.setAstCount(asset.getAstCount()+changeAsset.getChageastCount());
				}
				asset.setPrice(asset.getPrice()+changeAsset.getChagePrice());
				asset.setAmount(asset.getAmount()+changeAsset.getChageAmount());
				assetListUpdate.add(asset);
			}else if(changeAsset.getXz().trim().equals("9")){
				asset.setXz(changeAsset.getXz().trim());
				asset.setDeptNo(changeAsset.getChageDeptNo().trim());
				assetListUpdate.add(asset);
			}else{ 
				assetListDel.add(asset);
			}
			changeAssetList.add(changeAsset);
		}
		if (this.getChangeAssetDao().LastChangeAuditUpdate(changeAssetList)){
			 this.getAssetDao().deleteAll(assetListDel);
			 return 0;
		}
		else
			return 1;
		}catch(Exception e){
			e.printStackTrace();
			return 1;
		}
	}

	public int astChangeLastAuditBack(String auditNoArray, String returreas)
			throws Exception {
		// TODO Auto-generated method stub
		String auditNo[] = auditNoArray.split(",");
		ChangeAsset changeasset = null;
		List<ChangeAsset> changeassetList = new ArrayList<ChangeAsset>();
		for (int i = 0; i < auditNo.length; i++) {
			changeasset = new ChangeAsset();
			changeasset.setId(Integer.parseInt(auditNo[i]));
			changeassetList.add(changeasset);
		}
		if (this.getChangeAssetDao().backChangeAstLastAudit(changeassetList,returreas))
			return 0;
		else
			return 1;
	}
	public int ChangeRecoveryApplyAduit(String auditNoArray) throws Exception {
		// TODO Auto-generated method stub
		String auditNo[] = auditNoArray.split(",");
		ChangeAsset changeAsset = null;
		Asset asset =null;
		try{
		List<ChangeAsset> changeAssetList = new ArrayList<ChangeAsset>(); //处置对象列表
		List<Asset> assetListUpdate = new ArrayList<Asset>();  //存储主表更新（单位转移、增减值）对象
		List<Asset> assetListSave = new ArrayList<Asset>(); //存储其他处置 主表还原对象
			for (int i = 0; i < auditNo.length; i++) {
				changeAsset = new ChangeAsset();
				asset = new Asset();
				changeAsset = this.getChangeAssetDao().get(Integer.parseInt(auditNo[i]));
				if (changeAsset.getXz().trim().equals("1")) { // 现状为1 增减值时
					asset = this.getChangeAssetDao().findOneAstByNo(changeAsset.getAstNo().trim());
					asset.setPrice(asset.getPrice()- changeAsset.getChagePrice());
					asset.setAmount(asset.getAmount()- changeAsset.getChageAmount());
					if (changeAsset.getChageastCount() != 1) {
						asset.setAstCount(asset.getAstCount()- changeAsset.getChageastCount());
					}
					asset.setXz("1");
					assetListUpdate.add(asset);
				} else if (changeAsset.getXz().trim().equals("9")) {
					asset = this.getChangeAssetDao().findOneAstByNo(changeAsset.getAstNo().trim());
					asset.setDeptNo(changeAsset.getDeptNo());
					asset.setXz("1");
					assetListUpdate.add(asset);
				} else {
					BeanUtils.copyProperties(changeAsset, asset); //对象转换工具
					asset.setXz("1");
					assetListSave.add(asset);
				}
				changeAssetList.add(changeAsset); // 存储处置表对象 [用作恢复完删除]
			}
			if (assetListUpdate != null && assetListUpdate.size() > 0) {
				this.getAssetDao().saveOrUpdateAll(assetListUpdate);
			}
			if (assetListSave != null && assetListSave.size() > 0) {
				this.getAssetDao().saveAll(assetListSave);
			}
			if (changeAssetList != null && changeAssetList.size() > 0) {
				this.getChangeAssetDao().deleteAll(changeAssetList);
			}
			 return 0;
		}catch(Exception e){
			e.printStackTrace();
			 return 1;
		}
	}
    /**
     * 处置结果导出EXCEL
     */
	@SuppressWarnings("unchecked")
	public Pagination findExcelExportByExample(Pagination pagination,
			ChangeAsset chageasset, String deptNo, int findType)
			throws Exception {
		// TODO Auto-generated method stub
		if (pagination == null) {
			pagination = new Pagination();
		}
		if (chageasset == null)
			chageasset = new ChangeAsset();
		String hql = "FROM ChangeAsset a,Dept d WHERE a.deptNo=d.deptNo";
		if (!deptNo.trim().equals("00")) {
			hql += " AND a.deptNo LIKE '" + deptNo.trim() + "%'";
		}
		if(findType==1){
			hql+=" AND (a.aduit=0 or a.aduit=1)";
		}else{
			hql+=" AND a.aduit=7";
		}
		hql+=HqlUtil.bean2HqlLike(chageasset,"a");
		List list = this.getChangeAssetDao().findByHql(
				hql + " ORDER BY a." + pagination.getOrderBy() + " "
						+ pagination.getOrderType(), pagination);

		List<ChangeAsset> chageassetList = new ArrayList();

		for (int i = 0; i < list.size(); i++) {
			Object[] obj = (Object[]) list.get(i);
			ChangeAsset cast = (ChangeAsset) obj[0];
			cast.setNowStatus(this.gmkDao.findSomFieldByName("现状",chageasset.getXz().trim()));
			cast.setFundSub(this.gmkDao.findSomFieldByName("经费来源",chageasset.getJfly().trim()));
			cast.setUseDir(this.gmkDao.findSomFieldByName("使用方向",chageasset.getSyfx().trim()));
			cast.setAstSource(this.gmkDao.findSomFieldByName("资产来源",chageasset.getZcly().trim()));
			cast.setChargeOffDept(this.gmkDao.findSomFieldByName("拟核销财务科室",chageasset.getFinDeptName().trim()));
			cast.setAstClassName(this.gmkDao.findSomFieldByName("资产类别",chageasset.getAstClass().trim()));
			cast.setFinAccountName(this.gmkDao.findSomFieldByName("财务账户",chageasset.getFinAccount().trim()));
			
			cast.setDept((Dept) obj[1]);
			chageassetList.add(cast);
		}
		pagination.setResult(chageassetList);
		pagination.setRowcount(this.getChangeAssetDao().findCount(hql));
		return pagination;
	}
}
